1. MongoDB Delete Operations
Definition
MongoDB provides various methods to delete documents from collections. The main delete operations are deleteOne() and deleteMany(). These operations allow you to remove documents that match specific criteria, helping you maintain and clean your database effectively.
Algorithm 1: Basic Document Deletion :-
Example 1: Delete Single Document
// Delete a single user by username
db.users.deleteOne({
username: "john_doe"
})
Algorithm 2: Multiple Document Deletion :-
Example 2: Delete Multiple Documents
// Delete all expired products
db.products.deleteMany({
expiryDate: {
$lt: new Date()
}
})
Algorithm 3: Conditional Deletion :-
Example 3: Conditional Delete with Multiple Criteria
// Delete inactive users with specific criteria
db.users.deleteMany({
$and: [
{ lastLogin: { $lt: new Date(Date.now() - 30*24*60*60*1000) } },
{ status: "inactive" },
{ accountType: "trial" }
]
})